package com.tianji.learning.mq;

import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;

/**
 * @author ffk
 * @date 2024/6/28 21:42
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class likeTimesChangeListener {

     private final  IInteractionReplyService interactionReplyService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "qa.liked.times.queue", durable = "true"),
            exchange= @Exchange(name=LIKE_RECORD_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenLikedTimesChange(List<LikedTimesDTO> likedTimesDTO) {
        if(ObjectUtils.isEmpty(likedTimesDTO)){
            log.error("点赞次数消息变更异常");
            return;
        }
        log.info("qa.liked.times.queue 收到消息,点赞数变更了：{}", likedTimesDTO);
        //更新
        List<InteractionReply> newReplyList=new ArrayList<>(likedTimesDTO.size());

        for (LikedTimesDTO currentEntity : likedTimesDTO) {
            InteractionReply interactionReply = new InteractionReply();
            interactionReply.setLikedTimes(currentEntity.getLikedTimes());
            interactionReply.setId(currentEntity.getBizId());
            newReplyList.add(interactionReply);
        }

        //批量更新
        interactionReplyService.updateBatchById(newReplyList);

    }
}
